﻿using System.IO.Compression;
using System.Net.Http.Json;
using Common;

namespace QQGroupAlbumDownloader
{
    public class AlbumHelper
    {
        private readonly HttpClient _client = new();

        public async ValueTask<List<AlbumInfo>> GetAlbumList(AlbumRequestConfig config)
        {
            var dic = new Dictionary<string, string>
            {
                ["g_tk"] = config.Token,
                ["qzonetoken"] = config.QZoneToken,
                ["qunId"] = config.GroupId,
                ["uin"] = config.Uin,
                ["start"] = "0",
                ["num"] = "1000",
                ["format"] = "json",
                ["inCharset"] = "utf-8",
                ["outCharset"] = "utf-8",
                ["platform"] = "qzone",
                ["source"] = "qzone",
                ["cmd"] = "qunGetAlbumList",
                ["inCharset"] = "utf-8",
            };
            var queryString = new FormUrlEncodedContent(dic);
            var requestUrl =
                "https://h5.qzone.qq.com/proxy/domain/u.photo.qzone.qq.com/cgi-bin/upp/qun_list_album_v2?" +
                await queryString.ReadAsStringAsync();
            var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            // 添加cookie到请求头
            request.Headers.Add("Cookie", config.Cookie);
            var response = await _client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var res = await response.Content.ReadFromJsonAsync<AlbumListResponse<AlbumListData>>();
                return res?.Data?.Album?.OrderByDescending(x => x.CreateTime).Select(x => new AlbumInfo
                {
                    Id = x.Id,
                    Title = x.Title,
                    PhotoCount = x.PhotoCnt,
                    CreateAt = DateTime.Parse(x.CreateTime).Date,
                    UpdateAt = DateTime.Parse(x.UpdateTime).Date
                }).ToList();
            }

            NLogManager.Warning(@$"获取相册列表为空，群Id：{config.GroupId}");
            return null;
        }

        public async ValueTask<string> GetDownloadUrl(AlbumRequestConfig config, AlbumInfo info)
        {
            var queryDic = new Dictionary<string, string>
            {
                ["g_tk"] = config.Token,
                ["qzonetoken"] = config.QZoneToken,
            };
            var queryString = new FormUrlEncodedContent(queryDic);
            var requestUrl = "https://h5.qzone.qq.com/proxy/domain/app.photo.qq.com/cgi-bin/app/cgi_arch_photo_v2?" +
                             await queryString.ReadAsStringAsync();
            var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);

            var bodyDic = new Dictionary<string, string>
            {
                ["uin"] = config.Uin,
                ["hostUin"] = "-1",
                ["refer"] = "refer",
                ["source"] = "qzone",
                ["platform"] = "qzone",
                ["format"] = "json",
                ["inCharset"] = "utf-8",
                ["outCharset"] = "utf-8",
                ["appid"] = "422",
                ["selectMode"] = "1",
                ["albumid"] = info.Id,
                ["hostid"] = config.GroupId,
                ["albumName"] = info.Title,
            };
            request.Content = new FormUrlEncodedContent(bodyDic);
            // 添加cookie到请求头
            request.Headers.Add("Cookie", config.Cookie);
            var response = await _client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var res = await response.Content.ReadFromJsonAsync<AlbumListResponse<AlbumDownloadData>>();
                return res?.Data?.DownloadUrl;
            }
            NLogManager.Warning(@$"获取相册 {info.Title} 下载地址为空，群Id：{config.GroupId}");
            return null;
        }

        /// <summary>
        /// 下载文件并解压到指定路径
        /// </summary>
        /// <param name="downloadUrl">文件下载地址</param>
        /// <param name="extractPath">解压目标路径</param>
        /// <returns>操作是否成功</returns>
        public async Task<bool> DownloadAndExtractFileAsync(string downloadUrl, string extractPath)
        {
            try
            {
                // 下载文件到临时路径
                var tempFilePath = Path.GetTempFileName();
                using (var response = await _client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();

                    await using (var stream = await response.Content.ReadAsStreamAsync())
                    await using (var fileStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
                    {
                        await stream.CopyToAsync(fileStream);
                    }
                }

                // 创建解压目录（如果不存在）
                if (!Directory.Exists(extractPath))
                {
                    Directory.CreateDirectory(extractPath!);
                }

                // 解压文件
                ZipFile.ExtractToDirectory(tempFilePath, extractPath, true);

                // 移动所有子目录文件到上级目录
                foreach (var subDir in Directory.GetDirectories(extractPath))
                {
                    foreach (var file in Directory.GetFiles(subDir))
                    {
                        var destFile = Path.Combine(extractPath, Path.GetFileName(file));
                        File.Move(file, destFile, true);
                    }
                    Directory.Delete(subDir, true);
                }

                // 删除临时文件
                File.Delete(tempFilePath);

                return true;
            }
            catch (Exception ex)
            {
                // 可以添加日志记录异常信息
                NLogManager.Error(ex.Message);
            }

            return false;
        }
    }

    public class AlbumRequestConfig
    {
        public string Cookie { get; set; }

        public string Token { get; set; }

        public string QZoneToken { get; set; }

        public string Uin { get; set; }

        public string GroupId { get; set; }
    }

    public class AlbumInfo
    {
        /// <summary>
        /// 
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 大班回忆册
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int PhotoCount { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public DateTime UpdateAt { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public DateTime CreateAt { get; set; }
    }

    public class AlbumItem
    {
        /// <summary>
        /// 
        /// </summary>
        public int BHeight { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int BWidth { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string CoverUrl { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int CpX { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int CpY { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string CreateNickname { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string CreateTime { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int CreateUin { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string Desc { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int PhotoCnt { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int Privacy { get; set; }

        /// <summary>
        /// 大班回忆册
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string UpdateTime { get; set; }
    }

    public class AlbumListData
    {
        /// <summary>
        /// 
        /// </summary>
        public List<AlbumItem> Album { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int AlbumTotalPhoto { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int Offset { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string T { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int Total { get; set; }
    }

    public class AlbumDownloadData
    {
        /// <summary>
        /// 
        /// </summary>
        public string DownloadUrl { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int PhotoTotal { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string T { get; set; }
    }

    public class AlbumListResponse<T>
    {
        /// <summary>
        /// 
        /// </summary>
        public int Code { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int SubCode { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int Default { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public T Data { get; set; }
    }

}
